<?php

namespace app\services;

use plugin\admin\app\model\Good;
use plugin\admin\app\model\Option;
use plugin\admin\app\model\Order;
use Yansongda\Pay\Pay;

class AlipayService
{
    public static function config()
    {
        $config = config('payment');
        $alipay = Option::where('name', 'alipayInfo')->value('value');
        $alipay = json_decode($alipay, true);
        $config['alipay']['default']['app_id'] = $alipay['app_id'];
        $config['alipay']['default']['app_secret_cert'] = $alipay['app_secret_cert'];
        return $config;
    }

    public static function pay($params,$order)
    {
        $config = self::config();
        $config['alipay']['default']['return_url'] =  'https://car.ydk1.cn/h5/index.html#/?id='.$params['goods_unique_id'];
        Pay::config($config);
        $goods = Good::where('id', $order->goods_id)->first();
        return Pay::alipay()->h5([
            'out_trade_no' => $order['sn'],
            'total_amount' => $order['reward_total_price'],
            'subject' => $goods->name.'-定金支付',
            'quit_url' =>  'https://car.ydk1.cn/h5/index.html#/?id='.$params['goods_unique_id'],
        ]);

    }

    public static function notify($params)
    {
        Pay::config(config('payment'));
        // 2. 支付宝回调处理
        try {
            $result = Pay::alipay()->callback($params);
        }catch (\Throwable $e){
            dd($e->getMessage());
        }
        try {
            if (!empty($result) && ($result->trade_status == 'TRADE_SUCCESS' || $result->trade_status == 'TRADE_FINISHED')){
                $order = Order::where('sn', $result->out_trade_no)->first();
                $order->is_pay = 1;
                $order->pay_time = $result->gmt_payment;
                $order->pay_method = 2;
                $order->pay_no = $result->trade_no;
                RedisQueue::orderNotify(['sn'=>$result->out_trade_no]);
                $order->save();
            }
        }catch (\Throwable $e){
            throw new \Exception($e->getMessage());
        }


    }

}